package com.rpc.netty.core.config;

import com.rpc.netty.core.client.RpcClient;
import com.rpc.netty.core.registry.ServiceDiscovery;
import com.rpc.netty.core.registry.ServiceRegistry;
import com.rpc.netty.core.server.RpcServer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自动配置类
 *
 * @author david
 */
@Configuration
@EnableConfigurationProperties(RpcProperties.class)
public class NettyRpcAutoConfiguration {
    //客户端
    @Bean
    @ConditionalOnProperty(name = "rpc.client.registry")
    public RpcClient rpcClient(ServiceDiscovery serviceDiscovery) {
        return new RpcClient(serviceDiscovery);
    }

    @Bean
    @ConditionalOnProperty(name = "rpc.client.registry")
    public ServiceDiscovery serviceDiscovery(RpcProperties rpcProperties) {
        String registry = rpcProperties.getClient().getRegistry();
        return new ServiceDiscovery(registry);
    }

    //服务端
    @Bean
    @ConditionalOnProperty(name = "rpc.server.registry")
    public RpcServer rpcServer(RpcProperties rpcProperties, ServiceRegistry serviceRegistry) {
        String address = rpcProperties.getServer().getAddress();
        return new RpcServer(address, serviceRegistry);
    }

    @Bean
    @ConditionalOnProperty(name = "rpc.server.registry")
    public ServiceRegistry serviceRegistry(RpcProperties rpcProperties) {
        String registry = rpcProperties.getServer().getRegistry();
        return new ServiceRegistry(registry);
    }

}
